<?php


class messageControlPage extends commonControlPage {

    public function messageModule() {
        $opt = $_REQUEST['opt'];
        $opt = $opt ? $opt : 'list';

        $this->view->menu_name = $this->user['username'];
        $this->view->menu_group_name = '短消息';

        call_user_func(array($this,"{$opt}Action"));
    }

    private function listAction() {
        $total = $_ENV['db']->fetchCol("SELECT count(1) FROM sms WHERE tid = '{$this->user['uid']}' AND reply_id = '0'");
        
        $pager = new class_pager();
        $pager->setConfig((int)$_GET['page_no'],$total);
        $pager->setUrl('?app=message&mod=message&opt=list&page_no=tpt','tpt');

        $smslist = $_ENV['db']->fetchAll("SELECT * FROM sms WHERE `tid` = '{$this->user['uid']}' AND reply_id = '0' order by sms_id LIMIT ".$pager->getLimit()." OFFSET ".$pager->getOffset());

        $this->view->smslist = $smslist;
        $this->view->pager = $pager->output();
        $this->view->headlink = '<a href="?app=message&mod=message&opt=send">发信</a>';
        $this->view->node_name = '我的收件箱';
        $this->showMainPage('admincp/message_list');
    }

    private function sendAction() {
        if (POST && AJAX) {
            $data = getRequests(array('receive_name','content'));

            if (!$data['receive_name'] || !$data['content']) {
                $this->outputJson(0,'请检查输入');
            }

            if ($data['receive_name'] == $this->user['username']) {
                $this->outputJson(0,'不能给自己发送短消息');
            }

            $user = $_ENV['db']->fetch("SELECT * FROM admincp_member WHERE `username` = '{$data['receive_name']}'");
            if (!$user) {
                $this->outputJson(0,'接收方不存在');
            }

            $setsql = $this->buildSql(array(
                    'fid' => $this->user['uid'],
                    'fname' => $this->user['username'],
                    'tid' => $user['uid'],
                    'tname' => $user['username'],
                    'content' => htmlspecialchars($data['content']),
                    'dateline' => time()
                ));

            $_ENV['db']->runSql("INSERT INTO sms {$setsql}");

            $this->outputJson(1,'发送成功!');
        }

        $this->view->node_name = '发送短消息';

        $this->view->addScript("autocomplete");
        $this->showMainPage('admincp/message_send');
    }

    private function getuserAction() {
        $q = $_REQUEST['q'];

        $data = array();

        if (!empty($q)) {
            $data = (array)$_ENV['db']->fetchAll("SELECT * FROM admincp_member WHERE `username` LIKE '{$q}%'");
        }

        echo json_encode($data);
    }
}